<template>
  <div class="image-library-container">
    <!-- 控制区 -->
    <div class="controls">
      <!-- 搜索框 -->
      <div class="search-container">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索图片..." 
          class="search-input"
        />
        <img 
          src="@/assets/picture/find.png" 
          @click="filterImages" 
          alt="搜索" 
          class="search-icon" 
        />
       </div>
    </div>

    <!-- 图片展示区 -->
    <div class="image-gallery">
      <template v-if="filteredImages.length > 0">
      <div 
        v-for="(image) in paginatedImages" 
        :key="image.resource_id" 
        class="image-item"
      >
        <div class="image-container" @click="openImage(image.resource_url)">
          <img :src="image.resource_url" :alt="image.resource_name" class="gallery-image" />
         <div class="favorite-icon" @click.stop="toggleFavorite(image)">
          <img 
            :src="image.isFavorite ? require('@/assets/picture/star-solid.png') : require('@/assets/picture/star.png')" 
            :alt="image.isFavorite ? '已收藏' : '未收藏'" 
          />
        </div>
        </div>
        <div class="image-details" style="width:100%">
          <span class="image-name">{{ image.resource_name }}</span>
        </div>
      </div>
       </template>
        <div v-else class="empty-state">
          <img src="@/assets/picture/nostart.png" alt="无结果" class="empty-image">
          <p class="empty-text">暂时没有找到符合条件的资源哦</p>
        </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <button class="btn" @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>当前页: {{ currentPage }} / {{ totalPages }}</span>
      <button class="btn" @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { fetchStudentResources} from '@/services/api';
import { addStudentFavorite, removeStudentFavorites } from '@/services/api';

export default {
  name: 'ImagesPage',
  setup( ) {
    const userId = ref(localStorage.getItem("id"));
    const router = useRouter();
    const techId = ref(null);
    const token = ref(null);
    const currentPage = ref(1);
    const itemsPerPage = 15;
    const images = ref([]);
    const filteredImages = ref([]);
    const searchQuery = ref('');

    const fetchImageResources = () => {
      if (!techId.value) {
        console.error('Tech ID is missing. Redirecting to login page.');
        router.push('/login');
        return;
      }

      fetchStudentResources(techId.value, 'pic')
        .then(response => {
          if (response.data.status === 1) {
            images.value = response.data.data.map(image => ({
              ...image,
              isFavorite: true,  // 默认未收藏
                re_star_id: image.re_star_id || null
            }));
            filteredImages.value = images.value;
          } else {
            console.error('获取图片失败:', response.data.msg);
            if (response.data.status === 'NOT_LOGIN') {
              router.push('/login');
            }
          }
        })
        .catch(error => {
          console.error('请求错误:', error);
        });
    };

    const filterImages = () => {
      if (searchQuery.value) {
        filteredImages.value = images.value.filter(image =>
          image.resource_name.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
      } else {
        filteredImages.value = images.value;
      }
      currentPage.value = 1; // 重置到第一页
    };

    const paginatedImages = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredImages.value.slice(start, end);
    });

    const totalPages = computed(() => Math.ceil(filteredImages.value.length / itemsPerPage));

    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++;
      }
    };

    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--;
      }
    };

    const openImage = (ImageUrl) => {
      window.open(ImageUrl, "_blank");
    };

  

    onMounted(() => {
      const storedTechId = localStorage.getItem('id');
      const storedToken = localStorage.getItem('token');

      if (storedTechId && storedToken) {
        techId.value = storedTechId;
        token.value = storedToken;
        fetchImageResources();
      } else {
        console.error('User is not logged in. Redirecting to login page.');
        router.push('/login');
      }
    });
    const toggleFavorite = async (image) => {
  if (image.isFavorite) {
    // 取消收藏
    try {
      const res = await removeStudentFavorites(image.re_star_id);
      if (res.data.status === 1) {
        image.isFavorite = false;
        image.re_star_id = null;
        ElMessage.success('取消收藏成功');
      } else {
        ElMessage.error('取消收藏失败');
      }
    } catch (err) {
      console.error('取消收藏失败:', err);
      ElMessage.error('网络错误，取消收藏失败');
    }
  } else {
    // 添加收藏
    try {
      const res = await addStudentFavorite({
        user_id: userId.value,
        resource_id: image.resource_id
      });
      if (res.data.status === 1) {
        image.isFavorite = true;
        // 若后端返回 re_star_id 可在此赋值
        // image.re_star_id = res.data.data?.re_star_id;
        ElMessage.success('收藏成功');
      } else {
        ElMessage.error('收藏失败');
      }
    } catch (err) {
      console.error('收藏失败:', err);
      ElMessage.error('网络错误，收藏失败');
    }
  }
};
    return {
      techId,
      token,
      currentPage,
      itemsPerPage,
      images,
      filteredImages,
      paginatedImages,
      totalPages,
      searchQuery,
      filterImages,
      nextPage,
      prevPage,
      openImage,
      toggleFavorite
    };
  },
};
</script>


<style scoped>
.favorite-icon {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: white;
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
  box-shadow: 0 2px 6px rgba(0,0,0,0.2);
  z-index: 10;
}

.favorite-icon img {
  width: 16px;
  height: 16px;
}

.image-item:hover .favorite-icon {
  opacity: 1;
}
.image-library-container {
  min-height: 70vh;
  padding: 20px;
}

.controls {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  margin-right: 20px;
}

.search-input {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 200px;
  font-size: 16px;
  padding-right: 35px;
  border-radius: 20px;
  margin-right: 10px;
}

.search-icon {
  cursor: pointer;
  width: 20px; /* 图标的宽度 */
  height: 20px; /* 图标的高度 */
  margin-left: -40px; /* 将图标放置在输入框内 */
  margin-top: 7px;
}

.upload-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px; /* 添加合适的内边距 */
  border: none;
  border-radius: 4px; /* 圆角 */
  cursor: pointer;
  margin-left: 10px;
  transition: background-color 0.3s;
}

.upload-btn:hover {
  background-color: #3987d4; /* 悬停效果 */
}

.image-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
}

.image-item {
  position: relative;
  width: 150px;
  height: 200px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px;
  background-color: #fff;
  transition: border 0.3s ease; /* 添加边框变化效果 */
}

.image-container {
  position: relative;
  width: 120px;
  height: 100%;
  cursor: pointer; /* 鼠标悬停时显示手型 */
}

.gallery-image {
  width: 100%;
  height: 100%; /* 充满卡片内容 */
  object-fit: cover; /* 确保图片保持比例 */
  border-radius: 8px;
  transition: transform 0.3s ease; /* 添加缩放过渡效果 */
  margin-bottom:5px; ;
}

.image-item:hover .gallery-image {
  transform: scale(0.9); /* 鼠标经过时缩小图片 */
}

.image-item:hover {
  border: 2px solid #2196f3; /* 鼠标经过时显示边框 */
}


.image-item:hover .delete-btn {
  opacity: 1; /* 鼠标经过时显示按钮 */
}

.image-details {
  overflow: hidden; /* 溢出隐藏 */
  white-space: nowrap; /* 不换行 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  font-size: 12px;
  color: #527ebecc;
  /* background-color: #80808021; */
  width: 100%;
  text-align: center;
  height: 40px;
}

.image-name {
  max-width: 100%; /* 确保名字不超出 */
}


.pagination {
    gap: 10px;
    flex-wrap: wrap;
    position: absolute;
    bottom: 20px;
    left: 35%;
}

.pagination button {
  padding: 8px 12px;
  margin: 0 5px;
  cursor: pointer;
  background-color: #2196f3;
  color: #fff;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.pagination button:disabled {
  background-color: #b0bec5;
  cursor: not-allowed;
}

.pagination span {
  font-size: 16px;
  color: #333;
}

/* 新增样式，使查看和删除按钮与上传按钮样式一致 */
.action-btn {
  background-color: #125AA2;
  color: #fff;
  padding: 8px 12px; /* 添加合适的内边距 */
  border: none;
  border-radius: 4px; /* 圆角 */
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-btn:hover {
  background-color: #3987d4; /* 悬停效果 */
}
.empty-state {
  width: 780px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.empty-image {
  width: 400px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.empty-text {
  color: #888;
  font-size: 16px;
  margin-top: -60px;
}

/* 修改分页定位 */
.image-library-container {
  position: relative;
}


</style>

